#!/bin/bash
# ==========================================================
# 修改 RK3588 Debian rootfs 镜像 (ext4)
# 用法: sudo ./modify_rk_rootfs.sh <rootfs.img> [可选: apt-packages]
# 示例: sudo ./modify_rk_rootfs.sh debian_rootfs.img vim htop
# 适配: Ubuntu 主机, RK3588 arm64 rootfs
# ==========================================================

set -e  # 出错即退出

ROOTFS_IMG=${1:-debian_rootfs.img}  # 默认镜像名
MNT_DIR="/mnt/rootfs"               # 挂载点
APT_PACKAGES=${2:-""}               # 可选: 逗号分隔的 apt 包，如 "vim,htop"

if [[ ! -f "$ROOTFS_IMG" ]]; then
    echo "❌ 镜像文件不存在: $ROOTFS_IMG"
    exit 1
fi

echo "🔧 开始修改 $ROOTFS_IMG (RK3588 Debian rootfs)"
echo "📂 挂载点: $MNT_DIR"

# -----------------------------------------
# 检查依赖
# -----------------------------------------
for cmd in mount umount qemu-aarch64-static chroot; do
    if ! command -v $cmd >/dev/null 2>&1; then
        echo "❌ 缺少命令: $cmd，请安装: sudo apt install qemu-user-static binfmt-support rsync e2fsprogs"
        exit 1
    fi
done

# -----------------------------------------
# 挂载 rootfs
# -----------------------------------------
sudo mkdir -p $MNT_DIR
sudo mount -o loop $ROOTFS_IMG $MNT_DIR

# 绑定系统目录
sudo mount --bind /proc $MNT_DIR/proc
sudo mount --bind /sys $MNT_DIR/sys
sudo mount --bind /dev $MNT_DIR/dev
sudo mount --bind /dev/pts $MNT_DIR/dev/pts

# 注入 QEMU (arm64 模拟)
sudo cp /usr/bin/qemu-aarch64-static $MNT_DIR/usr/bin/ || echo "⚠️ QEMU 复制失败（可能已存在）"

# 设置 DNS (网络支持)
sudo cp /etc/resolv.conf $MNT_DIR/etc/resolv.conf

echo "✅ rootfs 已挂载到 $MNT_DIR"

# -----------------------------------------
# 可选: 自动 apt 安装包
# -----------------------------------------
if [[ -n "$APT_PACKAGES" ]]; then
    echo "📦 自动安装 apt 包: $APT_PACKAGES"
    PACKAGES=$(echo $APT_PACKAGES | tr ',' ' ')
    sudo chroot $MNT_DIR /bin/bash -c "apt update && apt install -y $PACKAGES"
    echo "✅ apt 安装完成"
fi

# -----------------------------------------
# 进入交互 chroot (手动修改)
# -----------------------------------------
echo "🛠️ 进入 chroot 环境 (arm64 Debian)，输入 'exit' 退出修改模式..."
sudo chroot $MNT_DIR /bin/bash -l  # -l 加载登录 shell

# -----------------------------------------
# 卸载并清理
# -----------------------------------------
echo "🧹 正在卸载和清理..."
sudo rm -f $MNT_DIR/usr/bin/qemu-aarch64-static
sudo umount $MNT_DIR/dev/pts
sudo umount $MNT_DIR/dev
sudo umount $MNT_DIR/sys
sudo umount $MNT_DIR/proc
sudo umount $MNT_DIR
sudo rmdir $MNT_DIR 2>/dev/null || true

# 验证镜像
echo "🔍 校验镜像..."
sudo e2fsck -fy $ROOTFS_IMG || echo "⚠️ 校验有警告，但继续"

echo "✅ 修改完成！镜像已更新: $ROOTFS_IMG"
echo "💡 下一步: 检查大小 (ls -lh $ROOTFS_IMG)，然后重新打包固件 (mkupdate.sh)"